#include<bits/stdc++.h>
using namespace std;

unordered_map<string,string> fath;
string s;
string fa;
string cur;

string find(string cur){
    if(fath[cur]==cur) return cur;
    return fath[cur] = find(fath[cur]);
}

int main(){
    while(true){
        cin>>s;
        if(s[0]=='$') break;
        
        if(s[0]=='#'){
            fa = s.substr(1);
            if(!fath.count(fa)){
                fath[fa] = fa;
            }
        }
        else if(s[0]=='+'){
            cur = s.substr(1);
            fath[cur] = find(fa);
        }
        else if(s[0]=='?'){
            cur = s.substr(1);
            cout<<cur<<' '<<find(cur)<<endl;
        }
    }
    return 0;
}